import logging
import os
import time

import netmiko
from django.shortcuts import render,redirect,HttpResponse
from ..models import Device
from ..utlis.get_snmp import snmpv2_get
from django.utils.safestring import mark_safe,SafeString
from netmiko import ConnectHandler
import re
import asyncio

import sys

import logging

logger = logging.getLogger("reboot")

def xunjian(request):


    if request.method == 'GET':
        return render(request, "xunjian.html")

    cpu_info = request.POST.get('cpu')
    mem_info = request.POST.get('MEM')
    devices_info = request.POST.get('wendu')
    stack_info = request.POST.get('stack')
    ap_info = request.POST.get("AP")
    diqu = request.POST.get("grade")
    result = []
    result.append("<h3>以下是运行结果：</h3>")

    dev = Device.objects.filter(diqu=diqu)
    """
    巡检CPU
    """
    async def hw_ssh(ip, user, pawd):
        async with asyncssh.connect(
                ip,
                port=22,
                username=user,
                password=pawd,
                known_hosts=None
        ) as conn:
            result1 = await conn.run('display cpu-usage | include CPU utilization\n', check=True, )
            list_cpu = re.search('CPU utilization for five seconds: (\d+)%: one minute: (\d+)%: five minutes: (\d+)%',
                                 result1.stdout).groups()
            result.append(f"<font size='4'>{i.ip_address}运行结果为：当前利用率：<b>%s</b>；1分钟内利用率：<b>%s</b>；5分钟内利用率：<b>%s</b> </font>"%(list_cpu[0] + "%", list_cpu[1] + "%", list_cpu[2] + "%")+'\n\n\n')
            await asyncio.sleep(2)

    if cpu_info:
        tasks = []
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            for i in dev:
                if i.dev_name == 'cisco':
                    tasks.append(loop.create_task(hw_ssh(i.ip_address, i.username, i.password)))
                elif i.dev_name == 'huawei':
                    tasks.append(loop.create_task(hw_ssh(i.ip_address, i.username, i.password)))
            loop.run_until_complete(asyncio.wait(tasks))
        except (OSError, asyncssh.Error) as exc:
            sys.exit('SSH connection failed: ' + str(exc))



    """巡检内存"""
    if mem_info:
        for i in dev:
            if i.dev_name == 'cisco':
                pass
            elif i.dev_name == 'huawei':
                # result.append(f"<h4>{i.ip_address}运行结果为：</h4>")
                switch = {'host': i.ip_address, 'username': i.username, 'password': i.password, 'device_type': 'huawei'}
                session = ConnectHandler(**switch)
                output_mem = session.send_command('display memory-usage')
                list_mem = re.findall('Memory Using Percentage Is: (\d+)%', output_mem)
                result.append(
                    f"<font size='4'>{i.ip_address}运行结果为：内存使用率：<b>%s</b></font>" % (list_mem[0] + "%")  + '\n\n\n')


    """巡检设备环境，风扇和电源"""
    if devices_info:
        for i in dev:
            if i.dev_name == 'cisco':
                pass
            elif i.dev_name == 'huawei':
                switch = {'host': i.ip_address, 'username': i.username, 'password': i.password, 'device_type': 'huawei'}
                session = ConnectHandler(**switch)
                output_env = session.send_command('display device')
                list_env = output_env.split('\n')
                list_env1 = []
                healthy_env = True
                for l in list_env:
                    if 'PowerOff' in l:
                        healthy_env = False
                        list_env1.append('Poweroff')
                    else:
                        list_env1.append('OK')
                if healthy_env == False:
                    result.append(f'<h4>{i.ip_address} has environment problems !!!</h4>')
                else:
                    result.append(f"<font size='4'>{i.ip_address} environment OK</font>")



    """查看设备堆叠信息"""
    if stack_info:
        for i in dev:
            if i.dev_name == 'cisco':
                pass
            elif i.dev_name == 'huawei':
                switch = {'host': i.ip_address, 'username': i.username, 'password': i.password, 'device_type': 'huawei'}
                session = ConnectHandler(**switch)
                output1 = session.send_command('display stack port',delay_factor=4)
                output2 = session.send_command('display stack peers',delay_factor=4)
                list1 = output1.split('\n')[7:]
                list2 = output2.split('\n')[3:]
                healthy1 = True
                healthy2 = True
                for l in list1:
                    if 'down' in l:
                        healthy1 = False
                    else:
                        pass
                if healthy1 == True:
                    result.append(f"<font size='4'>{i.ip_address} 堆叠端口状态正常</font> \n\n\n")
                else:
                    result.append(f"<h4>{i.ip_address} 堆叠端口状态错误 !!!</h4> \n\n\n")

                for m in list2:
                    if 'None' in m:
                        healthy2 = False
                    else:
                        pass
                if healthy2 == True:
                    result.append(f'<font size="4">{i.ip_address} Switch OK</font> \n\n\n')
                else:
                    result.append(f'<h4>{i.ip_address} Switch Status ERROR !!!</h4> \n\n\n')


    """统计AP设备利用率"""
    if ap_info:
        host={
        "device_type":"cisco_ios",
        "ip":"10.55.1.19",
        "username":"admin",
        "password":"shopee123@"
        }
        ssh = netmiko.ConnectHandler(**host)
        output = ssh.send_command("show ap dot11 5ghz load-info")
        if os.path.exists("ap-info.txt"):
            os.remove("ap-info.txt")
            with open("ap-info.txt","w") as f:
                f.write(output)
        else:
            with open("ap-info.txt","w") as f:
                f.write(output)
        f = open("ap-info.txt", "r")
        for i in f.readlines():
            if "CHNQDI" in i:
                if int(i.split()[3]) > 50 or int(i.split()[4]) > 50:
                    result.append(f"<font size='4'>%s：当前利用率为：<b>%s</b>，客户端连接数为：<b>%s</b></font> <br>" % (i.split()[0],i.split()[3]+"%",i.split()[4]))
                else:
                    pass
    result = mark_safe('\n'.join(result))
    return render(request, "check.html", {'result': result})
